package com.atguigu.flink.charkoer11;

import com.atguigu.flink.been.LoginEvent;
import com.atguigu.flink.utils.AtguiguUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

public class ProjectLoginLog {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.readTextFile("input/LoginLog.csv")
                .map((MapFunction<String, LoginEvent>) value -> {
                    String[] line = value.split(",");
                    return new LoginEvent(
                            Long.valueOf(line[0]),
                            line[1],
                            line[2],
                            Long.valueOf(line[3]) * 1000
                    );
                })
                .keyBy(LoginEvent::getUserId)
                .countWindow(2, 1)
                .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                    @Override
                    public void process(Long key,
                                        Context contctxext,
                                        Iterable<LoginEvent> elements,
                                        Collector<String> out) throws Exception {
                        List<LoginEvent> list = AtguiguUtil.tolist(elements);
                        if (list.size() == 2) {
                            LoginEvent loginEvent = list.get(0);
                            LoginEvent loginEvent1 = list.get(1);

                            Long eventTime = loginEvent.getEventTime();
                            Long eventTime1 = loginEvent1.getEventTime();

                            String type1 = loginEvent.getEventType();
                            String type2 = loginEvent1.getEventType();

                            if ("fail".equals(type1) && "fail".equals(type2) && Math.abs(eventTime - eventTime1) <= 2000) {
                                out.collect("有问题，不公平，我要重赛");
                            }
                        }
                    }
                }).print();


        env.execute();
    }
}
